package com.itsu.app.interceptor;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.itsu.commons.annotations.NoInterceptor;
import com.itsu.interfaces.entity.UserEntity;
import com.itsu.pojo.constants.Constants;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        if (((HandlerMethod) handler).hasMethodAnnotation(NoInterceptor.class)) {
            return true;
        }

        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            response.setStatus(401);
            return false;
        }

        JWT jwt = JWTUtil.parseToken(token).setKey(Constants.JWT_SECRET.getBytes());


        if (!jwt.verify() || !jwt.validate(0)) {
            response.setStatus(401);
            return false;
        }

        Long uid = Convert.toLong(jwt.getPayload("uid"));
        String phone = Convert.toStr(jwt.getPayload("phone"));

        UserEntity userEntity = UserEntity.builder().id(uid).mobile(phone).build();
        UserThreadLocal.set(userEntity);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
